package com.hq.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hq.zb.dto.UserDto;
import com.hq.zb.entity.CurrentUser;
import com.hq.zb.exception.BizException;
import com.hq.zb.exception.BizExceptionEnum;
import com.hq.zb.mapper.*;
import com.hq.zb.model.*;
import com.hq.zb.service.ICodeRulesHeaderService;
import com.hq.zb.service.IUserService;
import com.hq.zb.utils.BCryptUtils;
import com.hq.zb.vo.SelectCommVo;
import com.hq.zb.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户管理服务实体类
 * @author huanghanrui
 * @date 2022-03-19
 */
@Service
@RefreshScope
@Transactional(rollbackFor= Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private RoleUserMapper roleUserMapper;

    @Autowired
    private UserMenuMapper userMenuMapper;

/*    @Autowired
    private UserDeptMapper userDeptMapper;*/

    @Override
    public void saveUser(UserDto userDto) {
        User user = new User();
        BeanUtil.copyProperties(userDto, user);
        user.setEnableFlag(true);
        //新建用户的部门不允许为空
        if (CollectionUtil.isEmpty(userDto.getDeptCodes())) {
            throw new BizException(BizExceptionEnum.DATA_NOT_NULL, "必须选择用户所属部门.");
        } else {
            Wrapper<Dept> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("delete_flag", false);
            entityWrapper.eq("dept_code", userDto.getDeptCodes().get(0));
            List<Dept> depts = deptMapper.selectList(entityWrapper);
            if (CollectionUtil.isNotEmpty(depts)) {
                user.setOrgCode(depts.get(0).getOrgCode());
            }
        }
        if (CollectionUtil.isEmpty(userDto.getRoleIds())) {
            throw new BizException(BizExceptionEnum.DATA_NOT_NULL, "必须选择用户角色.");
        }
        if (StringUtils.isBlank(user.getUserName())) {
            throw new BizException(BizExceptionEnum.DATA_NOT_NULL, "用户名称必填.");
        }
        if (StringUtils.isBlank(user.getMobile())) {
            throw new BizException(BizExceptionEnum.DATA_NOT_NULL, "手机号必填.");
        }
        Wrapper<User> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("user_name", user.getUserName());
        List<User> users = userMapper.selectList(entityWrapper);
        if (user.getUserId() == null) {
            if (StringUtils.isNotEmpty(user.getMobile())) {
                //新增用户，默认初始化密码
                String bcpwd = BCryptUtils.hashpw(user.getMobile(), BCrypt.gensalt());
                user.setPassword(bcpwd);
            }
            if (CollectionUtil.isNotEmpty(users)) {
                throw new BizException(BizExceptionEnum.DATA_NOT_ONLY, "用户名称系统中已存在.");
            }
            userMapper.insert(user);
        } else {
            if (CollectionUtil.isNotEmpty(users)) {
                users = users.stream().filter(x-> user.getUserId() != x.getUserId()).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(users)) {
                    throw new BizException(BizExceptionEnum.DATA_NOT_ONLY, "用户名称系统中已存在.");
                }
            }
            userMapper.updateById(user);
        }
        /*//保存用户所属部门关系
        Wrapper<UserDept> wrapper = new EntityWrapper<>();
        entityWrapper.eq("user_id", user.getUserId());
        userDeptMapper.delete(wrapper);
        for (String deptCode : userDto.getDeptCodes()) {
            UserDept userDept = new UserDept();
            userDept.setUserId(user.getUserId());
            userDept.setDeptCode(deptCode);
            userDeptMapper.insert(userDept);
        }*/
        //保存用户角色
        List<Integer> roles = userDto.getRoleIds();
        List<Integer> roleIds = roleUserMapper.queryRoleIds(user.getUserId());
        boolean flag = roles.containsAll(roleIds);
        if (!flag) {
            //删除用户菜单
            UserMenu userMenu = new UserMenu();
            userMenu.setUserId(user.getUserId());
            userMenuMapper.deleteUserMenu(userMenu);
            //删除用户角色
            RoleUser roleUser = new RoleUser();
            userMenu.setUserId(user.getUserId());
            roleUserMapper.deleteRoleUser(roleUser);
            //保存
            for (Integer rId : roles) {
                RoleUser roleu = new RoleUser();
                roleu.setUserId(user.getUserId());
                roleu.setRoleId(rId);
                roleUserMapper.insert(roleu);
            }
        }
    }

    @Override
    public void deleteUser(List<User> users) {
        if (CollectionUtil.isNotEmpty(users)) {
            for (User user : users) {
                user.setDeleteFlag(true);
                userMapper.updateById(user);
                //删除用户菜单关系
                UserMenu userMenu = new UserMenu();
                userMenu.setUserId(user.getUserId());
                userMenuMapper.deleteUserMenu(userMenu);
                //删除用户角色关系
                RoleUser roleUser = new RoleUser();
                userMenu.setUserId(user.getUserId());
                roleUserMapper.deleteRoleUser(roleUser);
            }
        }
    }

    @Override
    public Page<UserVo> listByPage(Page<UserVo> page, Wrapper<UserVo> wrapper) {
        page.setRecords(userMapper.listByPage(page, wrapper));
        return page;
    }

    @Override
    public List<UserDto> queryList(UserDto userDto, CurrentUser currentUser) {
        if (StringUtils.isNotEmpty(currentUser.getOrgCode())) {
            userDto.setOrgCode(currentUser.getOrgCode());
        }
        return userMapper.queryList(userDto);
    }
}
